<template>
  <div id="app">
    <el-button @click="selectEnterpriseContact">选人</el-button>
    <el-button @click="checkIsSupportSoterAuthentication">检测识别</el-button>
    <el-button @click="checkIsSoterEnrolledInDevice">查询生物信息是否录入</el-button>
    <el-button @click="startSoterAuthentication">信息认证</el-button>
    <el-button @click="bioassayAuthentication">人脸识别</el-button>

    <el-button @click="openLocation">打开地图</el-button>
    <el-button @click="openQQMap">打开QQ地图</el-button>
    <el-input v-model="keyword" placeholder="请输入关键词"></el-input>
    <el-button @click="searchKeyword">搜索</el-button>
    <el-button @click="searchAddress">地址解析</el-button>
    <el-button @click="searchLatLng">反地址解析</el-button>
    <el-button @click="searchCityByName">城市名查询</el-button>
    <el-form ref="form" :model="form" label-width="80px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="起点">
            <el-input v-model="form.start" placeholder="起点"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="终点">
            <el-input v-model="form.end" placeholder="终点"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计算策略">
            <el-select v-model="form.policy" placeholder="计算策略">
              <el-option label="最少时间" value="LEAST_TIME"></el-option>
              <el-option label="最短距离" value="LEAST_DISTANCE"></el-option>
              <el-option label="避开高速" value="AVOID_HIGHWAYS"></el-option>
              <el-option label="实时路况" value="REAL_TRAFFIC"></el-option>
              <el-option label="预测路况" value="PREDICT_TRAFFIC"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-checkbox v-model="form.sp">显示路段地标</el-checkbox>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="选择起点">
            <el-select v-model="form.starts" placeholder="选择起点"></el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="选择终点">
            <el-select v-model="form.ends" placeholder="选择终点"></el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="reSearch">查询线路</el-button>
        </el-col>
      </el-row>
    </el-form>
    <!--   定义地图显示容器   -->
    <div style="width:603px;height:300px;" id="container"></div>
    <div style='width: 500px; height: 180px' id="infoDiv"></div>
  </div>
</template>

<script>
  export default {
    name: 'app',
    data() {
      return {
        keyword: '武汉长江大桥',
        markers: [],
        map: null,
        searchService: null,//搜索
        geocoder: null, //地址解析
        directionsService: null,
        cityService: null,
        telephone: 18938890589,
        form: {
          start: '银科大厦',
          end: '天坛公园'
        },
        directionsLabels: [],
        directionsPlacemarks: [],
        routeSteps: [],
        stepLine: null,
        startMarker: null,
        endMarker: null,
        routeLines: [],
        directionsRoutes: [],
        routeSteps: [],
        polyline: null,
        routeLines: [],
        routesDesc: []
      }
    },
    mounted() {
      this.initDirectionsService();
      this.initMap();
      this.initCityService();
      this.initSearchService();
      this.initGeocoder();
      this.calcRoute();
    },
    methods: {
      selectEnterpriseContact() {
        this.$wx.invoke("selectEnterpriseContact", {
            "fromDepartmentId": -1,// 必填，表示打开的通讯录从指定的部门开始展示，-1表示自己所在部门开始, 0表示从最上层开始
            "mode": "multi",// 必填，选择模式，single表示单选，multi表示多选
            "type": ["department", "user"]// 必填，选择限制类型，指定department、user中的一个或者多个
          }, function (res) {
            console.log(res);
            if (res.err_msg == "selectEnterpriseContact:ok") {
              if (typeof res.result == 'string') {
                res.result = JSON.parse(res.result) //由于目前各个终端尚未完全兼容，需要开发者额外判断result类型以保证在各个终端的兼容性
              }
              console.log(res.result);
            }
          }
        );
      },
      checkIsSupportSoterAuthentication() {
        this.$wx.invoke("checkIsSupportSoterAuthentication", {}, function (res) {
          if (res.err_msg != "checkIsSupportSoterAuthentication:ok") {
            //错误处理
            console.log(res.err_msg);
          } else {
            // res.supportMode = [] 不具备任何被SOTER支持的生物识别方式
            // res.supportMode = ['fingerPrint'] 只支持指纹识别
            // res.supportMode = ['fingerPrint', 'facial'] 支持指纹识别和人脸识别
          }
        });
      },
      checkIsSoterEnrolledInDevice() {
        this.$wx.invoke("checkIsSoterEnrolledInDevice", { checkAuthMode: "fingerPrint" }, function (res) {
          if (res.err_msg != "checkIsSoterEnrolledInDevice:ok") {
            //错误处理
            console.log(res.err_msg)
          } else {
            console.log(res.isEnrolled)
          }
        });
      },
      startSoterAuthentication() {
        this.$wx.invoke("startSoterAuthentication", {
          requestAuthModes: ["facial", "fingerPrint"],
          challenge: "test_challenge",
          authContent: "请按指纹识别"
        }, function (res) {
          if (res.err_msg != "startSoterAuthentication:ok") {
            //错误处理
            console.log(res.err_msg)
          } else {
            console.log(res.authMode);// 认证方式
            console.log(res);//用户填写的挑战因子
          }
        });
      },
      bioassayAuthentication() {
        this.$wx.invoke('bioassayAuthentication', {
          name: '姓名', // 姓名
          idcard: '15、18位省份证号码' // 身份证号
        }, function (res) {
          if (res.err_msg == "bioassayAuthentication:ok") {
            console.log(res);
            var code = res.code; //检测成功
          } else {
            console.log(res);
            //错误处理
          }
        });
      },
      openLocation() {
        this.$wx.openLocation({
          // latitude: 0, // 纬度，浮点数，范围为90 ~ -90
          // longitude: 0, // 经度，浮点数，范围为180 ~ -180。
          name: '武汉', // 位置名
          address: '越秀财富中心', // 地址详情说明
          scale: 1, // 地图缩放级别,整形值,范围从1~28。默认为16
        });
      },
      openQQMap() {
        var map = new qq.maps.Map(document.getElementById("container"), {
          center: new qq.maps.LatLng(39.916527, 116.397128),      // 地图的中心地理坐标
          zoom: 8,     // 地图缩放级别
          mapStyleId: 'style1'  // 该key绑定的style1对应于经典地图样式，若未绑定将弹出无权限提示窗
        });
      },
      searchKeyword() {
        this.clearOverlays();
        this.search();
      },
      clearOverlays() {
        var overlay;
        while (overlay = this.markers.pop()) {
          overlay.setMap(null);
        }
      },
      initMap() {
        var center = new qq.maps.LatLng(39.916527, 116.397128);
        this.map = new qq.maps.Map(document.getElementById('container'), {
          center: center,
          zoom: 13
        });
        qq.maps.event.addListener(
          this.map,
          'click',
          function (event) {
            alert('您点击的位置为:[' + event.latLng.getLng() +
              ',' + event.latLng.getLat() + ']');
          }
        );
      },
      initSearchService() {
        var _this = this;
        var latlngBounds = new qq.maps.LatLngBounds();
        //设置Poi检索服务，用于本地检索、周边检索
        this.searchService = new qq.maps.SearchService({
          //设置搜索范围为北京
          location: "北京",
          //设置搜索页码为0
          pageIndex: 0,
          //设置每页的结果数为5
          pageCapacity: 5,
          //设置展现查询结构到infoDIV上
          panel: document.getElementById('infoDiv'),
          //设置动扩大检索区域。默认值true，会自动检索指定城市以外区域。
          autoExtend: true,
          //检索成功的回调函数
          complete: function (results) {
            //设置回调函数参数
            var pois = results.detail.pois;
            for (var i = 0, l = pois.length; i < l; i++) {
              var poi = pois[i];
              //扩展边界范围，用来包含搜索到的Poi点
              latlngBounds.extend(poi.latLng);

              (function (n) {
                var marker = new qq.maps.Marker({
                  map: _this.map
                });
                marker.setPosition(pois[n].latLng);

                marker.setTitle(i + 1);
                _this.markers.push(marker);

                qq.maps.event.addListener(marker, 'click', function () {
                  _this.$message({
                    message: pois[n].name,
                    type: 'success'
                  });
                });
              })(i);
            }
            //调整地图视野
            _this.map.fitBounds(latlngBounds);
          },
          //若服务请求失败，则运行以下函数
          error: function () {
            alert("出错了。");
          }
        });
      },
      initGeocoder() {
        var _this = this;
        _this.geocoder = new qq.maps.Geocoder({
          complete: function (result) {
            console.log(result);
            _this.map.setCenter(result.detail.location);
            var marker = new qq.maps.Marker({
              map: _this.map,
              position: result.detail.location
            });
            _this.markers.push(marker);
            qq.maps.event.addListener(marker, 'click', function () {
              _this.$message({
                message: result.detail.address,
                type: 'success'
              });
            });
          }
        });
      },
      initDirectionsService() {
        this.directionsService = new qq.maps.DrivingService({
          complete: function (response) {
            console.log('DrivingService')
            var start = response.detail.start,
              end = response.detail.end;
            this.form.starts = [], this.form.ends = [];
            for (var i = 0; i < start.length; i++) {
              var text = start[i].name;
              var value = start[i].latLng;
              this.form.starts.push({ value: text, label: value });
            }
            for (var i = 0; i < end.length; i++) {
              var text = end[i].name;
              var value = end[i].latLng;
              this.form.ends.push({ value: text, label: value });
            }
          }
        });
        this.calcRoute();
      },
      search() {
        var _this = this;
        _this.searchService.search(_this.keyword);
      },
      searchAddress() {
        this.clearOverlays();
        this.geocoder.getLocation(this.keyword);
      },
      searchLatLng() {
        var latlngStr = this.keyword.split(",", 2);
        var lat = parseFloat(latlngStr[0]);
        var lng = parseFloat(latlngStr[1]);
        var latLng = new qq.maps.LatLng(lat, lng);
        //调用获取位置方法
        this.clearOverlays();
        this.geocoder.getAddress(latLng);
      },
      initCityService() {
        var _this = this;
        this.cityService = new qq.maps.CityService({
          complete: function (result) {
            console.log(result);
            _this.map.setCenter(result.detail.latLng);
            var marker = new qq.maps.Marker({
              map: _this.map,
              position: result.detail.latLng
            });
            _this.markers.push(marker);
            qq.maps.event.addListener(marker, 'click', function () {
              _this.$message({
                message: result.detail.latLng,
                type: 'success'
              });
            });
          }
        });
      },
      searchCityByName() {
        this.clearOverlays();
        this.cityService.searchCityByName(this.keyword);
      },
      calcRoute() {
        this.directionsService.setLocation("北京");
        this.directionsService.setPolicy(qq.maps.DrivingPolicy[this.form.policy]);
        this.directionsService.search(this.form.start, this.form.end);
      },
      //显示路段路标
      showP() {
        var showPlacemark = this.form.sp;
        if (showPlacemark) {
          for (var i = 0; i < this.directionsPlacemarks.length; i++) {
            var placemarks = this.directionsPlacemarks[i];
            for (var j = 0; j < placemarks.length; j++) {
              var placemark = placemarks[j];
              var label = new qq.maps.Label({
                map: this.map,
                position: placemark.latLng,
                content: placemark.name
              });
              this.directionsLabels.push(label);
            }
          }
        } else {
          this.clearOverlays(this.directionsLabels);
        }
      },
      renderStep(index) {
        var step = this.routeSteps[index];
        //clear overlays;
        this.stepLine && this.stepLine.setMap(null);
        //draw setp line
        this.stepLine = new qq.maps.Polyline(
          {
            path: step.path,
            strokeColor: '#ff0000',
            strokeWeight: 6,
            map: this.map
          }
        )
      },
      reSearch() {
        var s_latLng = this.form.starts;
        var e_latLng = this.form.ends;
        var s = s_latLng.split(",");
        var e = e_latLng.split(",");
        var start = new qq.maps.LatLng(Number(s[0]), Number(s[1]));
        var end = new qq.maps.LatLng(Number(e[0]), Number(e[1]));

        this.search(start, end);
        this.directionsService.setComplete(function (response) {
          var start = response.detail.start,
            end = response.detail.end;
          var anchor = new qq.maps.Point(6, 6),
            size = new qq.maps.Size(24, 36),
            start_icon = new qq.maps.MarkerImage(
              'https://lbs.qq.com/javascript_v2/img/busmarker.png',
              size,
              new qq.maps.Point(0, 0),
              anchor
            ),
            end_icon = new qq.maps.MarkerImage(
              'https://lbs.qq.com/javascript_v2/img/busmarker.png',
              size,
              new qq.maps.Point(24, 0),
              anchor
            );
          this.startMarker && this.startMarker.setMap(null);
          this.endMarker && this.endMarker.setMap(null);
          this.clearOverlays(this.routeLines);

          this.startMarker = new qq.maps.Marker({
            icon: start_icon,
            position: start.latLng,
            map: this.map,
            zIndex: 1
          });
          this.endMarker = new qq.maps.Marker({
            icon: end_icon,
            position: end.latLng,
            map: this.map,
            zIndex: 1
          });
          this.directionsRoutes = response.detail.routes;
          var routes_desc = [];
          //所有可选路线方案
          for (var i = 0; i < this.directionsRoutes.length; i++) {
            var route = this.directionsRoutes[i],
              legs = route;
            //调整地图窗口显示所有路线
            map.fitBounds(response.detail.bounds);
            //所有路程信息
            //for(var j = 0 ; j < legs.length; j++){
            var steps = legs.steps;
            this.routeSteps = steps;
            this.polyline = new qq.maps.Polyline(
              {
                path: route.path,
                strokeColor: '#3893F9',
                strokeWeight: 6,
                map: this.map
              }
            );
            this.routeLines.push(polyline);
            //所有路段信息
            for (var k = 0; k < steps.length; k++) {
              var step = steps[k];
              //路段途经地标
              this.directionsPlacemarks.push(step.placemarks);
              //转向
              var turning = step.turning,
                img_position;
              ;
              switch (turning.text) {
                case '左转':
                  img_position = '0px 0px'
                  break;
                case '右转':
                  img_position = '-19px 0px'
                  break;
                case '直行':
                  img_position = '-38px 0px'
                  break;
                case '偏左转':
                case '靠左':
                  img_position = '-57px 0px'
                  break;
                case '偏右转':
                case '靠右':
                  img_position = '-76px 0px'
                  break;
                case '左转调头':
                  img_position = '-95px 0px'
                  break;
                default:
                  img_position = '';
                  break;
              }
              var turning_img = '&nbsp;&nbsp;<span' +
                ' style="margin-bottom: -4px;' +
                'display:inline-block;background:' +
                'url(https://lbs.qq.com/javascript_v2/img/turning.png) no-repeat ' +
                img_position + ';width:19px;height:' +
                '19px"></span>&nbsp;';
              var p_attributes = [
                'onclick="renderStep(' + k + ')"',
                'onmouseover=this.style.background="#eee"',
                'onmouseout=this.style.background="#fff"',
                'style="margin:5px 0px;cursor:pointer"'
              ].join(' ');
              this.routesDesc.push('<p ' + p_attributes + ' ><b>' + (k + 1) +
                '.</b>' + turning_img + step.instructions);
            }
            //}
          }
          //方案文本描述
          var routes = document.getElementById('infoDiv');
          routes.innerHTML = routes_desc.join('<br>');
        })
      }
    }
  }
</script>

<style scoped>
  html, body {
    width: 100%;
    height: 100%;
  }

  * {
    margin: 0px;
    padding: 0px;
  }

  body {
    font: 12px/16px Verdana, Helvetica, Arial, sans-serif;
  }
</style>
